package com.example.housemanage

import android.app.AlertDialog
import android.content.Context
import android.widget.Toast
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder

/**
 * 建筑列表适配器类
 * @param data 建筑组数据列表
 * @param activity 房屋管理活动实例
 */
class BuildingAdapter(data: MutableList<HouseManageActivity.BuildingGroup>, private val activity: HouseManageActivity) : BaseQuickAdapter<HouseManageActivity.BuildingGroup, BaseViewHolder>(R.layout.item_building, data) {

    /**
     * 转换并绑定建筑组数据到视图
     * @param holder 视图持有者
     * @param item 建筑组数据项
     */
   override fun convert(holder: BaseViewHolder, item: HouseManageActivity.BuildingGroup) {
    // 设置建筑名称和面积信息
    holder.setText(R.id.tv_building_name, item.buildingName)
    holder.setText(R.id.tv_building_area, "${item.area}m²")

    // 获取箭头图标并根据展开状态设置相应图标
    val ivArrow = holder.getView<ImageView>(R.id.iv_arrow)
    ivArrow.setImageResource(
        if (item.expanded) R.drawable.ic_arrow_up else R.drawable.ic_arrow_down
    )

    // 获取房间列表RecyclerView并根据展开状态控制显示/隐藏
    val rvRoom = holder.getView<RecyclerView>(R.id.rv_room)
    rvRoom.visibility = if (item.expanded) View.VISIBLE else View.GONE

    // 避免重复设置LayoutManager和Adapter
    if (rvRoom.layoutManager == null) {
        rvRoom.layoutManager = LinearLayoutManager(activity)
    }

    var roomAdapter = rvRoom.adapter as? RoomAdapter
    if (roomAdapter == null) {
        roomAdapter = RoomAdapter(item.rooms.toMutableList()) { room ->
            // 调用Activity中的ViewModel删除房间
            activity.deleteRoom(room)
        }
        rvRoom.adapter = roomAdapter
        // 设置滑动删除功能
        roomAdapter.setupSwipeDelete(rvRoom, activity)
    } else {
        // 直接重新创建适配器（虽然性能不是最优，但能确保正常工作）
        roomAdapter = RoomAdapter(item.rooms.toMutableList()) { room ->
            // 调用Activity中的ViewModel删除房间
            activity.deleteRoom(room)
        }
        rvRoom.adapter = roomAdapter
        // 设置滑动删除功能
        roomAdapter.setupSwipeDelete(rvRoom, activity)
    }

    // 设置箭头点击事件，切换展开状态并刷新当前项
    ivArrow.setOnClickListener {
        item.expanded = !item.expanded
        // 只刷新需要改变的部分
        holder.setGone(R.id.rv_room, !item.expanded)
        ivArrow.setImageResource(
            if (item.expanded) R.drawable.ic_arrow_up else R.drawable.ic_arrow_down
        )

        // 更新房间列表数据
        rvRoom.adapter = RoomAdapter(item.rooms.toMutableList())
    }
}

}

